package com.tianlh.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author 黑子
 * @Date 2018/1/10 13:34
 */
public class ZKCount {

    /*
    * 分布式计数器：
    * 一个典型场景是统计系统的在线人数
    * 指定一个ZooKeeper数据节点作为计数器，多个应用实例在分布式锁的控制下，通过更新该数据节点的内容来实现计数功能。
    *
    * */

    static String path = "/zk_count";
    static RetryPolicy retry = new ExponentialBackoffRetry(1000, 3);
    static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
        .namespace("count").sessionTimeoutMs(5000).retryPolicy(retry).build();

    public static void main(String[] args) throws Exception {
        client.start();
        DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(client, path, retry);
        AtomicValue<Integer> rc = atomicInteger.add(1);
        System.out.println("Result:" + rc.succeeded());

    }
}
